<?php

namespace Users\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;
use Users\Form\RegisterForm;
use Users\Form\LoginForm;


class LoginController extends AbstractActionController
{
    protected $authservice;
    public function getAuthService()
    {
	if(!$this->authservice)
	{
	    /*$dbAdapter = $this->getServiceLocator()->get('Zend\Db\Adapter\Adapter');
	    $dbTableAuthAdapter = new DbTableAuthAdapter($dbAdapter, 'user','email','password', 'MD5(?)');
	    $authService = new AuthenticationService();
	    $authService->setAdapter($dbTableAuthAdapter);
	    $this->authservice = $authService;*/
            
            $this->authservice = $this->getServiceLocator()->get('AuthService');
	}
	return $this->authservice;
    }
    
    public function indexAction()
    {
        //$form = new LoginForm();
        $form = $this->getServiceLocator()->get('loginform');
        $request = $this->getRequest();
        
        if($request->isPost())
        {
            $form->setData($request->getPost());
            if($form->isValid())
            {
                $this->getAuthService()->getAdapter()
                                        ->setIdentity($request->getPost('email'))
                                        ->setCredential($request->getPost('password'));
                $result = $this->getAuthService()->authenticate();
                if($result->isValid())
                {
                    $this->getAuthService()->getStorage()->write($this->request->getPost('email'));
                    return $this->redirect()->toRoute(NULL , array( 
                                                    'controller' => 'login', 
                                                    'action' =>  'confirm' 
                                            ));			
                }
                else{
                    $model = new ViewModel(array(
					'error' => true,
					'form'  => $form,
				));
                    $model->setTemplate('users/login/index');
                    return $model;
                }
            }
        }
        return new ViewModel(array(
            'form' => $form
        ));
    }
    
    public function confirmAction()
    {
        $this->layout('layout/myaccount');
        $user_email = $this->getAuthService()->getStorage()->read();
	$viewModel  = new ViewModel(array(
            'user_email' => $user_email 
        )); 
        return $viewModel; 
    }
    
}
